from django.views import View
from django.http.response import JsonResponse, HttpResponseBadRequest
from casedemo13_ser.models import Student
from casedemo13_ser.serializer import Student1Serializer,Student1ModelSerializer
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import json
from django.shortcuts import render

class Student1View(View):
    """序列化器"""
    def get(self,request):
        """序列化一个模型对象"""
        # 1. 获取数据集
        student = Student.objects.all()
        # 2. 实例化序列化器，获取序列化对象，此处采用的序列器是Student1Serializer
        serializer = Student1Serializer(student,many=True) #  如果多个对象序列化 需要加many
        # 3. 调用序列化对象的data属性方法获取转换后的数据
        data = serializer.data
        # 4. 响应数据
        return JsonResponse(data=data, status=888, safe=False, json_dumps_params={"ensure_ascii": False})
    def post(self,request):
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        serializer = Student1Serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200, json_dumps_params={"ensure_ascii": False})
        return JsonResponse(serializer.errors, status=400)
    def put(self,request):
        """更新学生信息"""
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        stu_id = data.get("id")
        if not stu_id:
            return JsonResponse({'error': '必须提供学生ID进行更新'}, status=400)
        try:
            student = Student.objects.get(id=stu_id)
        except Student.DoesNotExist:
            return JsonResponse({'error': '学生不存在'}, status=404)
        serializer = Student1Serializer(student, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200, json_dumps_params={"ensure_ascii": False})
        return JsonResponse(serializer.errors, status=400)

    def delete(self,request):
        """删除学生信息"""
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        stu_id = data.get("id")
        if not stu_id:
            return JsonResponse({'error': '必须提供学生ID进行删除'}, status=400)
        try:
            student = Student.objects.get(id=stu_id)
            student.delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except Student.DoesNotExist:
            return JsonResponse({'error': '学生不存在'}, status=404)
"""
实现增删改查的相关操作即CRUD操作
此处的设想是前端的进行数据请求，然后实现数据的CRUD，
同时支持用户信息的id获取或者全部获取的方式
"""
@method_decorator(csrf_exempt, name='dispatch')
class Student1ViewDemo1(View):
    """序列化器"""
    def get(self, request):
        """查询单个或所有学生"""
        student_id = request.GET.get('id')
        if student_id:
            try:
                student = Student.objects.get(id=student_id)
                serializer = Student1Serializer(student)
                return JsonResponse(serializer.data, status=200, json_dumps_params={"ensure_ascii": False})
            except Student.DoesNotExist:
                return JsonResponse({'error': '学生不存在'}, status=404)
        else:
            students = Student.objects.all()
            serializer = Student1Serializer(students, many=True)
            return JsonResponse(serializer.data, status=200, safe=False, json_dumps_params={"ensure_ascii": False})

    def post(self, request):
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        serializer = Student1Serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200, json_dumps_params={"ensure_ascii": False})
        return JsonResponse(serializer.errors, status=400)

    def put(self, request):
        """更新学生信息"""
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        stu_id = data.get("id")
        if not stu_id:
            return JsonResponse({'error': '必须提供学生ID进行更新'}, status=400)
        try:
            student = Student.objects.get(id=stu_id)
        except Student.DoesNotExist:
            return JsonResponse({'error': '学生不存在'}, status=404)
        serializer = Student1Serializer(student, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200, json_dumps_params={"ensure_ascii": False})
        return JsonResponse(serializer.errors, status=400)

    def delete(self, request):
        """删除学生信息"""
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("请求体必须是JSON格式")
        stu_id = data.get("id")
        if not stu_id:
            return JsonResponse({'error': '必须提供学生ID进行删除'}, status=400)
        try:
            student = Student.objects.get(id=stu_id)
            student.delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except Student.DoesNotExist:
            return JsonResponse({'error': '学生不存在'}, status=404)



def view_HTML(request):
    return render(request, 'casedemo13/cruddemo1.html')